package com.ly.mpayment.rest.up.qgliantong;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.net.URLDecoder;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("qgliantong")
public class QuanGuoLtRest {

    //private String sid = "2c922ab771b1e4a00171b6b1bff00008";

    //private String key = "e3d342aeb7a7ebe911cbeee4051867e1";

    //private String notifyAddress = "http://115.29.174.229:8183/weiliu/client/qglt/callBack";

    Logger logger = Logger.getLogger(QuanGuoLtRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;

    /**
     * { "orderId":"4028b8815e200012fxx",
     * "shopuuid":"4028b8815f6e3524015f6e3b61ef0004", "amount":"100",
     * "sign":"3183496d7f0cb397b819bdc89a11c0fc",
     * "productuuid":"4028b8815f7d4ae2015f86ee6aa70009", "phoneNum":"18000001111",
     * "notifyAddress":"http://ip:port/callmethod", "ts":"20170928115522" }
     *
     * @return
     */
    public String commitOrder(String orderId, String amount, String productuuid, String phone,final String url,String sid,String notifyAddress,String key) {
        String ts = new DateUtils().toTimeStamp();
        JSONObject data = new JSONObject();
        data.put("orderId", orderId);
        data.put("uid", sid);
        data.put("amount", amount);
        data.put("pid", productuuid);
        data.put("phone", phone);
        data.put("notify", notifyAddress);
        data.put("ts", ts);
        data.put("sign", MD5.md5(StringSort.doSign(data).concat("&key="+key)));
        return HttpClient.post(url, data.toString());
    }

    @SuppressWarnings("static-access")
    @Path("callBack")
    @POST
    public String callBack(String data) {
        logger.info("guangmu_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            JSONObject jsonD = JSONObject.parseObject(data);
            UpOrder order = upOrderService.findById(jsonD.getString("orderId"));
            if (order != null && jsonD.getString("status").equals("2") && order.getStatus() == Config.status[0]) {
                order.setRemark(jsonD.containsKey("msg") ? URLDecoder.decode(jsonD.getString("msg") ) : "");
                RechargeRest.successUpOrder.add(order);
                return  "0";
            } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("status").equals("3")) {
                order.setRemark(URLDecoder.decode(jsonD.getString("msg")));
                RechargeRest.failtUpOrder.add(order);
                return "0";
            } else {
                logger.info("guangmu_not_found_order:" + jsonD.getString("orderId") + "," );
            }
        }
        return "0";
    }


    /**
     * 订单提交
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        String result = commitOrder(order.getUporderuuid(), order.getUpShopPro().getUpfacevalue(), order.getUpShopPro().getProductCode(), order.getUpphonenum(), shop.getOrderCommitAddress()
        ,shop.getAppId(),shop.getOrderCallAddress(),shop.getUpkey());
        logger.info("commitOrder_qglt:"+result);
        if (!StringUtils.isBlank(result) && !result.equals("404")) {
            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("code") && json.getString("code").equals("1000")) {
                this.upOrderService.updateUpOrderMsg(order, json.containsKey("data") ? json.getJSONObject("data").getString("oid") : "",json.getString("message"));
            } else if(json.containsKey("code") && errorCode.contains(json.getString("code"))) {
                order.setRemark(json.containsKey("message") ? json.getString("message") : json.getString("msg"));
                RechargeRest.failtUpOrder.add(order);
            }
        } else {
            this.upOrderService.updateUpOrderArtificial(order, "","提单失败,人工");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    /**
     * 1001	商户错误!
     * 1003	sign错误!
     * 1005	商家订单号已经存在 !
     * 1006	运营商错误 !
     * 1008	未识别的号码!
     * 1010	商户余额不足!（提单失败）
     * 1011	未找到产品!
     * 1012	回调地址错误 !
     * 1013	商户不存在或者商户编号错误!
     * 1014	充值金额错误,必须大于 0 !
     * 1016	充值号码与运营商不符!
     * 1017	充值号码省份与充值产品省份不正确
     * 1018	此号段禁止提单
     * 1019	渠道关闭,禁止提单
     * 1020	提交异常。须通过查询状态处理订单
     * 1021	提交异常。须通过查询状态处理订单
     */
    Set<String> errorCode = new HashSet<String>(){{
        add("1001");
        add("1003");
        add("1005");
        add("1006");
        add("1008");
        add("1010");
        add("1012");
        add("1011");
        add("1013");
        add("1014");
        add("1016");
        add("1017");
        add("1018");
        add("1019");
    }};

    /**
     * 订单查询
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        String ts = new DateUtils().toTimeStamp();
        JSONObject data = new JSONObject();
        data.put("oid", upOrder.getUporderuuid());
        data.put("uid", shopInfo.getAppId());
        data.put("ts", ts);
        data.put("sign", MD5.md5(StringSort.doSign(data).concat("&key="+shopInfo.getUpkey())));
        String result =  HttpClient.post(shopInfo.getOrderStatusAddress(), data.toString());
        logger.info("qgltqueryOrder:"+upOrder.getUpphonenum()+":"+result);
        if (!StringUtils.isBlank(result)) {
            JSONObject jsonD = JSONObject.parseObject(result);
            if(jsonD.containsKey("data") && jsonD.getString("code").equals("1000")){
                UpOrder order = upOrderService.findById(jsonD.getJSONObject("data").getString("oid"));
                if (order != null && jsonD.getJSONObject("data").getString("status").equals("2") && order.getStatus() == Config.status[0]) {
                    order.setRemark(jsonD.getJSONObject("data").containsKey("msg") ? jsonD.getJSONObject("data").getString("msg") : "");
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0]
                        && jsonD.getJSONObject("data").getString("status").equals("3")) {
                    order.setRemark(jsonD.getJSONObject("data").getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    logger.info("qglt_not_found_order:" + jsonD.getJSONObject("data").getString("orderId") + ",");
                }
            //备用方案
            }else if(jsonD.getString("code").equals("1004") && StringUtils.isBlank(upOrder.getUpOrderId())){
                UpOrder order = upOrderService.findById(jsonD.getJSONObject("data").getString("oid"));
                order.setRemark(jsonD.getString("message"));
                RechargeRest.failtUpOrder.add(order);
            }else{
                logger.info("qglt_not_found_order:" + jsonD.getJSONObject("data").getString("orderId") + "," );
            }
        }
    }

}
